import { httpService } from '@/utils/request'
import type { UploadFile, UploadResponse, FileListResponse } from './models'

/**
 * 上传文件
 * @param file 要上传的文件
 * @param onProgress 上传进度回调
 * @returns Promise<string> - 返回文件URL
 */
export function uploadFile(file: File, onProgress?: (percentage: number) => void): Promise<string> {
    const formData = new FormData()
    formData.append('file', file)

    const config: any = {
        headers: {
            'Content-Type': 'multipart/form-data'
        }
    }

    if (onProgress) {
        config.onUploadProgress = (progressEvent: any) => {
            if (progressEvent.total) {
                const percentage = Math.round((progressEvent.loaded * 100) / progressEvent.total)
                onProgress(percentage)
            }
        }
    }

    return httpService.post<string>('/upload/file', formData, undefined, undefined, config)
}

/**
 * 批量上传文件
 * @param files 要上传的文件数组
 * @param onProgress 上传进度回调
 * @returns Promise<UploadResponse[]>
 */
export function uploadFiles(files: File[], onProgress?: (percentage: number) => void): Promise<UploadResponse[]> {
    const formData = new FormData()
    files.forEach((file, index) => {
        formData.append(`files[${index}]`, file)
    })

    return httpService.post<UploadResponse[]>('/upload/files', formData, {
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        onUploadProgress: (progressEvent: any) => {
            if (progressEvent.total) {
                const percentage = Math.round((progressEvent.loaded * 100) / progressEvent.total)
                onProgress?.(percentage)
            }
        }
    } as any)
}

/**
 * 获取文件列表
 * @param params 查询参数
 * @returns Promise<FileListResponse>
 */
export function getFileList(params?: {
    page?: number
    size?: number
    type?: string
    keyword?: string
}): Promise<FileListResponse> {
    return httpService.get<FileListResponse>('/upload/files', { params })
}

/**
 * 删除文件
 * @param fileId 文件ID
 * @returns Promise<void>
 */
export function deleteFile(fileId: string): Promise<void> {
    return httpService.delete(`/upload/file/${fileId}`)
}

/**
 * 批量删除文件
 * @param fileIds 文件ID数组
 * @returns Promise<void>
 */
export function deleteFiles(fileIds: string[]): Promise<void> {
    return httpService.delete('/upload/files', { data: { fileIds } } as any)
}

/**
 * 获取文件信息
 * @param fileId 文件ID
 * @returns Promise<UploadFile>
 */
export function getFileInfo(fileId: string): Promise<UploadFile> {
    return httpService.get<UploadFile>(`/upload/file/${fileId}`)
}

/**
 * 下载文件
 * @param fileId 文件ID
 * @returns Promise<Blob>
 */
export function downloadFile(fileId: string): Promise<Blob> {
    return httpService.get(`/upload/download/${fileId}`, {
        responseType: 'blob'
    })
} 